import os
import requests
import time
from pathlib import Path
import shutil
import json
from config import *  # 导入所有配置

def detect_faces(image_path, retry=0):
    """使用CompreFace API检测图片中是否有人脸"""
    url = f"{COMPREFACE_BASE_URL}/api/v1/detection/detect"
    headers = {
        'x-api-key': DETECTION_API_KEY
    }
    
    try:
        with open(image_path, 'rb') as img_file:
            files = {'file': img_file}
            # 添加检测阈值参数
            data = {'det_prob_threshold': str(DET_PROB_THRESHOLD)}
            
            print(f"正在检测图片: {image_path} (阈值: {DET_PROB_THRESHOLD})")
            response = requests.post(
                url,
                headers=headers,
                files=files,
                data=data,
                timeout=TIMEOUT
            )
            
            if response.status_code == 200:
                result = response.json()
                print(f"API响应: {json.dumps(result, ensure_ascii=False, indent=2)[:300]}...")
                if 'result' in result and len(result['result']) > 0:
                    faces_count = len(result['result'])
                    print(f"✓ 检测到 {faces_count} 个人脸")
                    return True
                else:
                    print("✗ 未检测到人脸")
                    return False
            else:
                print(f"✗ 检测失败, 状态码: {response.status_code}")
                print(f"错误信息: {response.text}")
                return False
                
    except requests.exceptions.Timeout:
        print(f"请求超时: {image_path}")
        if retry < MAX_RETRIES:
            print(f"尝试重试 ({retry+1}/{MAX_RETRIES})...")
            time.sleep(2)  # 等待2秒后重试
            return detect_faces(image_path, retry+1)
        return False
        
    except requests.exceptions.ConnectionError as e:
        print(f"连接错误: {str(e)}")
        print("请检查CompreFace服务是否正在运行，以及API地址是否正确")
        if retry < MAX_RETRIES:
            print(f"尝试重试 ({retry+1}/{MAX_RETRIES})...")
            time.sleep(2)  # 等待2秒后重试
            return detect_faces(image_path, retry+1)
        return False
        
    except Exception as e:
        print(f"发生错误: {str(e)}")
        return False

def is_image_file(file_path):
    """检查文件是否为支持的图片格式"""
    return Path(file_path).suffix.lower() in IMAGE_EXTENSIONS

def process_directory(directory_path):
    """处理指定目录中的图片，删除不包含人脸的图片"""
    base_dir = Path(directory_path)
    
    # 确保目录存在
    if not base_dir.exists():
        print(f"错误: 目录不存在 {directory_path}")
        return
    
    # 创建一个备份目录，用于保存被删除的图片
    backup_dir = base_dir.parent / f"{base_dir.name}_no_face"
    backup_dir.mkdir(exist_ok=True)
    
    # 遍历目录中的所有文件
    for item in base_dir.iterdir():
        if item.is_file() and is_image_file(item):
            # 检测图片中是否有人脸
            has_face = detect_faces(str(item))
            
            if not has_face:
                # 如果没有人脸，将图片移动到备份目录
                backup_path = backup_dir / item.name
                print(f"移动无人脸图片到备份目录: {item.name}")
                shutil.move(str(item), str(backup_path))

def verify_api_key():
    """验证API密钥是否有效，并检查是否有人脸检测服务权限"""
    url = f"{COMPREFACE_BASE_URL}/api/v1/detection/detect"
    headers = {
        'x-api-key': DETECTION_API_KEY
    }
    
    try:
        # 只发送一个HEAD请求来验证API密钥
        response = requests.head(url, headers=headers, timeout=TIMEOUT)
        
        if response.status_code == 401:
            print("错误: API密钥无效或没有人脸检测服务的权限")
            print("请确保在CompreFace中创建了人脸检测服务并使用正确的API密钥")
            return False
        elif response.status_code == 403:
            print("错误: 没有权限访问人脸检测服务")
            return False
        elif response.status_code in [200, 405]:  # 405表示不支持HEAD方法但API密钥有效
            print("✓ API密钥验证成功")
            return True
        else:
            print(f"警告: API密钥验证返回未知状态码 {response.status_code}")
            return True  # 继续尝试
    except Exception as e:
        print(f"API密钥验证时发生错误: {str(e)}")
        return True  # 出错时仍继续尝试

def main():
    """主函数"""
    try:
        print(f"使用检测API密钥: {DETECTION_API_KEY[:8]}...{DETECTION_API_KEY[-8:]}")
        
        # 验证API密钥
        if not verify_api_key():
            return
            
        # 处理图片目录
        print(f"开始处理目录: {IMAGE_DIR}")
        process_directory(IMAGE_DIR)
        
        print("\n所有图片检查完成!")
        print(f"不包含人脸的图片已移动到 {IMAGE_DIR}_no_face 目录")
        
    except Exception as e:
        print(f"发生错误: {str(e)}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main() 